package com.campus.secondhand.controller;

import java.security.Principal;
import java.util.List;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.campus.secondhand.common.Result;
import com.campus.secondhand.entity.PurchaseRequest;
import com.campus.secondhand.entity.User;
import com.campus.secondhand.model.dto.PurchaseRequestCreateDTO;
import com.campus.secondhand.model.dto.PurchaseRequestStatusDTO;
import com.campus.secondhand.model.dto.PurchaseRequestUpdateDTO;
import com.campus.secondhand.model.vo.PurchaseRequestDetailVO;
import com.campus.secondhand.model.vo.PurchaseRequestVO;
import com.campus.secondhand.service.PurchaseRequestService;
import com.campus.secondhand.service.UserService;
import com.campus.secondhand.service.FavoriteService;

import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 求购信息控制器
 */
@RestController
@RequestMapping("/requests")
@RequiredArgsConstructor
public class PurchaseRequestController {

    private final PurchaseRequestService purchaseRequestService;
    private final UserService userService;
    private final FavoriteService favoriteService;
    private static final Logger log = LoggerFactory.getLogger(PurchaseRequestController.class);

    /**
     * 获取求购列表
     * 
     * @param sortBy 排序方式
     * @param page   页码
     * @param size   每页数量
     * @param userId 用户ID
     * @return 求购列表分页结果
     */
    @GetMapping
    public Result<Page<PurchaseRequestVO>> getRequestList(
            @RequestParam(required = false, defaultValue = "newest") String sortBy,
            @RequestParam(required = false, defaultValue = "1") int page,
            @RequestParam(required = false, defaultValue = "12") int size,
            @RequestParam(required = false) Long userId) {

        Sort sort;
        switch (sortBy) {
            case "priceAsc":
                sort = Sort.by("budget").ascending();
                break;
            case "priceDesc":
                sort = Sort.by("budget").descending();
                break;
            case "mostViewed":
                sort = Sort.by("views").descending();
                break;
            case "newest":
            default:
                sort = Sort.by("createTime").descending();
                break;
        }

        Pageable pageable = PageRequest.of(page - 1, size, sort);
        // 调用服务获取所有有效求购信息，筛选由前端完成
        return purchaseRequestService.getRequestList(null, null, null, null, null, pageable, userId);
    }

    /**
     * 发布求购信息
     * 
     * @param principal                当前登录用户
     * @param purchaseRequestCreateDTO 求购信息创建DTO
     * @return 创建结果
     */
    @PostMapping
    @PreAuthorize("isAuthenticated()")
    public Result<?> createRequest(Principal principal,
            @Validated @RequestBody PurchaseRequestCreateDTO purchaseRequestCreateDTO) {
        Result<User> userResult = userService.getByUsername(principal.getName());
        if (userResult.getCode() != 200) {
            return Result.error(userResult.getCode(), userResult.getMessage());
        }

        Long userId = userResult.getData().getId();
        return purchaseRequestService.createRequest(userId, purchaseRequestCreateDTO);
    }

    /**
     * 获取求购详情
     * 
     * @param id 求购ID
     * @return 求购详情
     */
    @GetMapping("/{id}")
    public Result<PurchaseRequestDetailVO> getRequestDetail(@PathVariable Long id) {
        return purchaseRequestService.getRequestDetail(id);
    }

    /**
     * 更新求购状态
     * 
     * @param id                       求购ID
     * @param principal                当前登录用户
     * @param purchaseRequestStatusDTO 状态更新DTO
     * @return 更新结果
     */
    @PutMapping("/{id}/status")
    @PreAuthorize("isAuthenticated()")
    public Result<?> updateRequestStatus(@PathVariable Long id, Principal principal,
            @Validated @RequestBody PurchaseRequestStatusDTO purchaseRequestStatusDTO) {
        Result<User> userResult = userService.getByUsername(principal.getName());
        if (userResult.getCode() != 200) {
            return Result.error(userResult.getCode(), userResult.getMessage());
        }

        Long userId = userResult.getData().getId();
        return purchaseRequestService.updateRequestStatus(id, userId, purchaseRequestStatusDTO);
    }

    /**
     * 删除求购信息
     * 
     * @param id        求购ID
     * @param principal 当前登录用户
     * @return 删除结果
     */
    @DeleteMapping("/{id}")
    @PreAuthorize("isAuthenticated()")
    public Result<?> deleteRequest(@PathVariable Long id, Principal principal) {
        Result<User> userResult = userService.getByUsername(principal.getName());
        if (userResult.getCode() != 200) {
            return Result.error(userResult.getCode(), userResult.getMessage());
        }

        Long userId = userResult.getData().getId();
        return purchaseRequestService.deleteRequest(id, userId);
    }

    /**
     * 编辑求购信息
     * 
     * @param id                       求购ID
     * @param principal                当前登录用户
     * @param purchaseRequestUpdateDTO 更新DTO
     * @return 更新结果
     */
    @PutMapping("/{id}")
    @PreAuthorize("isAuthenticated()")
    public Result<?> updateRequest(@PathVariable Long id, Principal principal,
            @Validated @RequestBody PurchaseRequestUpdateDTO purchaseRequestUpdateDTO) {
        Result<User> userResult = userService.getByUsername(principal.getName());
        if (userResult.getCode() != 200) {
            return Result.error(userResult.getCode(), userResult.getMessage());
        }

        Long userId = userResult.getData().getId();
        return purchaseRequestService.updateRequest(id, userId, purchaseRequestUpdateDTO);
    }

    /**
     * 增加浏览量
     * 
     * @param id 求购ID
     * @return 更新后的浏览量
     */
    @PostMapping("/{id}/view")
    public Result<?> increaseViews(@PathVariable Long id) {
        return purchaseRequestService.increaseViews(id);
    }

    /**
     * 联系发布者
     * 
     * @param id        求购ID
     * @param principal 当前登录用户
     * @param message   联系信息
     * @return 操作结果
     */
    @PostMapping("/{id}/contact")
    @PreAuthorize("isAuthenticated()")
    public Result<?> contactPublisher(
            @PathVariable Long id,
            Principal principal,
            @RequestBody String message) {
        Result<User> userResult = userService.getByUsername(principal.getName());
        if (userResult.getCode() != 200) {
            return Result.error(userResult.getCode(), userResult.getMessage());
        }

        Long userId = userResult.getData().getId();
        return purchaseRequestService.contactPublisher(id, userId, message);
    }

    /**
     * 收藏求购信息
     * 
     * @param id     求购信息ID
     * @param userId 用户ID（从请求体或URL参数中获取）
     * @return 操作结果
     */
    @PostMapping("/{id}/favorite")
    public Result<Object> favoriteRequest(
            @PathVariable Long id,
            @RequestParam(required = false) Long userId,
            @RequestBody(required = false) Object body) {

        log.info("收藏求购信息请求: id={}, userId={}, body={}", id, userId, body);

        // 从请求体中提取userId（如果存在）
        if (userId == null && body != null && body instanceof java.util.Map) {
            java.util.Map<?, ?> map = (java.util.Map<?, ?>) body;
            if (map.containsKey("userId")) {
                try {
                    userId = Long.valueOf(map.get("userId").toString());
                } catch (Exception e) {
                    log.error("解析userId失败", e);
                }
            }
        }

        // 验证userId是否存在
        if (userId == null) {
            return Result.error(400, "缺少用户ID");
        }

        // 验证用户是否存在
        User user = userService.getUserById(userId);
        if (user == null) {
            return Result.error(404, "用户不存在");
        }

        // 调用收藏服务添加收藏
        Result<Void> result = favoriteService.addPurchaseRequestFavorite(userId, id);

        if (result.getCode() == 200) {
            return Result.success(java.util.Map.of("favorited", true), "收藏成功");
        } else {
            return Result.error(result.getCode(), result.getMessage());
        }
    }

    /**
     * 取消收藏求购信息
     * 
     * @param id     求购信息ID
     * @param userId 用户ID（从URL参数中获取）
     * @return 操作结果
     */
    @DeleteMapping("/{id}/favorite")
    public Result<Object> unfavoriteRequest(
            @PathVariable Long id,
            @RequestParam(required = true) Long userId) {

        log.info("取消收藏求购信息请求: id={}, userId={}", id, userId);

        // 验证用户是否存在
        User user = userService.getUserById(userId);
        if (user == null) {
            return Result.error(404, "用户不存在");
        }

        // 调用收藏服务取消收藏
        Result<Void> result = favoriteService.removePurchaseRequestFavorite(userId, id);

        if (result.getCode() == 200) {
            return Result.success(java.util.Map.of("favorited", false), "取消收藏成功");
        } else {
            return Result.error(result.getCode(), result.getMessage());
        }
    }

    /**
     * 检查求购信息是否已收藏
     * 
     * @param id     求购信息ID
     * @param userId 用户ID（从URL参数中获取）
     * @return 是否已收藏
     */
    @GetMapping("/{id}/favorite")
    public Result<Object> checkFavorite(
            @PathVariable Long id,
            @RequestParam(required = true) Long userId) {

        log.info("检查求购信息收藏状态: id={}, userId={}", id, userId);

        // 验证用户是否存在
        User user = userService.getUserById(userId);
        if (user == null) {
            return Result.error(404, "用户不存在");
        }

        Boolean isFavorite = favoriteService.isPurchaseRequestFavorite(userId, id);
        return Result.success(java.util.Map.of("favorited", isFavorite), "获取成功");
    }
}